import pymysql


class DbTools(object):
    @staticmethod
    def db_connect():
        conn = pymysql.connect(host="211.103.136.244",
                               port=7061,
                               user="student",
                               password="iHRM_student_2022",
                               database="ihrm",
                               charset="utf8")
        return conn

    @staticmethod
    def query_all(sql):
        conn = None
        cursor = None
        try:
            conn = DbTools.db_connect()
            cursor = conn.cursor()
            cursor.execute(sql)
            ret = cursor.fetchall()
            return ret
        except Exception as err:
            print(f"抓到异常了：{err}")
        finally:
            cursor.close()
            conn.close()

    @staticmethod
    def db_idu(sql):
        conn = None
        cursor = None
        try:
            conn = DbTools.db_connect()
            cursor = conn.cursor()
            cursor.execute(sql)
            conn.commit()
            print("数据库操作完成")
        except Exception as err:
            print(f"抓到异常了：{err}")
            conn.rollback()

        finally:
            cursor.close()
            conn.close()


if __name__ == '__main__':
    ret = DbTools.query_all("select * from bs_user where mobile='13800000044';")
    print(ret)
    ret = DbTools.db_idu("update bs_user set username ='小趴菜' where mobile ='13800000044';")
    print(ret)
